import SelectSearch from "@/components/SelectSearch";
import Https from "@/utils/Https";
import {
  ProForm,
  ProFormColorPicker,
  ProFormDigit,
  ProFormRate,
  ProFormSelect,
  ProFormText,
  ProFormTimePicker,
} from "@ant-design/pro-components";
import { Button, Drawer, Empty, message, Select, Space, Spin } from "antd";
import dayjs from "dayjs";
import { FC, useEffect, useRef, useState } from "react";
import { courseDuration, disableWorkTime } from "../../interface";
import styles from "../styles.less";
const AddWork: FC<any> = (props) => {
  const { open, venueHours, onSuccess, onClose, venueObj, roomInfo, workDate } =
    props;
  const [courseInfo, setCourseInfo] = useState({});
  const [loading, setLoading] = useState(false);
  const formRef = useRef();
  //禁用时间区间
  const { disabledHours, disabledMinutes } = disableWorkTime(
    dayjs(venueHours.venueStart, "HH:mm"),
    dayjs(venueHours.venueEnd, "HH:mm"),
    15
  );
  const [coachList, setCoachList] = useState([]);
  const [courseList, setCourseList] = useState([]);
  const getCoachList = async (id) => {
    let params = {
      venueId: id,
    };
    let res = await Https.get("/employee/manage/listCoach", params, true);
    let objList = [];
    if (res.code == 200 && res.data) {
      if (res.data.length > 0) {
        res.data.map((e) =>
          objList.push({ label: e.nickName, value: e.userId })
        );
      }
    }
    setCoachList([...objList]);
  };
  const getCourseList = async (id) => {
    let params = {
      venueId: id,
      courseStatus: "0",
      courseType: "2",
    };
    let res = await Https.get("/course/sched/courseAllList", params, true);
    if (res.code == 200 && res.data) {
      setCourseList(res.data);
    } else {
      setCourseList([]);
    }
  };
  useEffect(() => {
    if (open) {
      setCourseInfo({});
      getCoachList(venueObj.id);
      getCourseList(venueObj.id);
    }
  }, [venueObj, open]);
  return (
    <Drawer
      title={`新增排课(${workDate})`}
      onClose={() => {
        setCourseInfo({});
        onClose();
      }}
      destroyOnClose={true}
      rootClassName={styles.addWorkClass}
      maskClosable={true}
      width="60%"
      open={open}
      extra={
        <Select
          placeholder="请选择课程"
          style={{ width: "300px" }}
          getPopupContainer={(triggerNode) => triggerNode.parentElement}
          onChange={(e) => {
            let objInfo = courseList.filter(function (o) {
              return o.id == e;
            })[0];
            setCourseInfo(objInfo);
            formRef?.current.setFieldsValue({
              ...objInfo,
              startTime: null,
              endTime: null,
              classRoom: roomInfo.classRoomName,
            });
          }}
        >
          {courseList &&
            courseList.length > 0 &&
            courseList.map((item) => (
              <Select.Option key={item.id} value={item.id}>
                {item.courseName}
              </Select.Option>
            ))}
        </Select>
      }
      footer={
        courseInfo.id && (
          <Space>
            <Button
              size="large"
              onClick={() => {
                setCourseInfo({});
                onClose();
              }}
            >
              取消
            </Button>
            <Button
              loading={loading}
              onClick={() => {
                formRef?.current
                  ?.validateFieldsReturnFormatValue()
                  .then(async (values) => {
                    let params = {
                      ...values,
                      id: 0,
                      venueId: venueObj.id,
                      courseType: "2",
                      courseId: courseInfo.id,
                      startTimeSlot: workDate + " " + values.startTime + ":00",
                      endTimeSlot: workDate + " " + values.endTime + ":00",
                      classRoom: roomInfo.id,
                    };
                    delete params.startTime;
                    delete params.endTime;
                    setLoading(true);
                    let res = await Https.post(
                      "/course/sched/addSchedule",
                      params,
                      true
                    );
                    setLoading(false);
                    if (res.code == 200) {
                      message.success("保存成功");
                      onSuccess();
                    } else {
                      message.error(res.msg);
                    }
                  })
                  .catch((errorInfo) => {
                    console.log(errorInfo, "-errorInfo");
                  });
              }}
              size="large"
              type="primary"
            >
              确定
            </Button>
          </Space>
        )
      }
    >
      <Spin spinning={loading}>
        <ProForm
          formRef={formRef}
          submitter={false}
          className={styles.addCourse}
        >
          {!courseInfo.id ? (
            <Empty
              image={Empty.PRESENTED_IMAGE_SIMPLE}
              description={<div>请先选择需要排课的课程</div>}
            />
          ) : (
            <>
              <ProFormSelect
                options={coachList}
                name="courseCoachId"
                label="授课老师"
                allowClear={false}
                fieldProps={{
                  getPopupContainer: (triggerNode) => triggerNode.parentElement,
                }}
                rules={[{ required: true, message: "请选择授课老师" }]}
              />
              <ProFormSelect
                options={courseDuration}
                name="courseDuration"
                label="单节课时长(分钟)"
                onChange={() => {
                  formRef?.current?.setFieldsValue({
                    startTime: null,
                    endTime: null,
                  });
                }}
                fieldProps={{
                  getPopupContainer: (triggerNode) => triggerNode.parentElement,
                }}
                rules={[{ required: true, message: "请选择单节课时长" }]}
              />
              <ProFormDigit
                label="人数"
                name="peopleNumMax"
                min={1}
                max={1000}
                rules={[{ required: true, message: "请输入可约人数" }]}
                fieldProps={{
                  suffix: "人",
                  precision: 0,
                  controls: false,
                }}
              />
              <ProFormText
                name="classRoom"
                label="上课教室"
                readonly
                rules={[{ required: true, message: "请选择上课教室" }]}
              />
              <ProForm.Group>
                <ProFormTimePicker
                  tooltip={"结束时间等于开始时间加课程时长"}
                  name="startTime"
                  label="开始时间-结束时间"
                  rules={[{ required: true, message: "请选择开始时间" }]}
                  onChange={(e) => {
                    let interval =
                      formRef?.current?.getFieldFormatValue("courseDuration");
                    let nowStartTime =
                      workDate + " " + dayjs(e).format("HH:mm:ss");
                    let endTime = dayjs(nowStartTime).add(interval, "minute");
                    let nowEndTime = dayjs(endTime).format(
                      "YYYY-MM-DD HH:mm:ss"
                    );
                    if (
                      dayjs(nowStartTime) < dayjs() ||
                      dayjs(nowEndTime) < dayjs()
                    ) {
                      message.error("排课时间已过期，不能进行排课!");
                      formRef?.current?.setFieldsValue({
                        startTime: null,
                        endTime: null,
                      });
                      return;
                    }
                    let venueEnd = workDate + " " + venueHours.venueEnd + ":00";
                    if (nowEndTime <= venueEnd) {
                      formRef?.current?.setFieldsValue({
                        endTime: dayjs(endTime).format("HH:mm"),
                      });
                    } else {
                      message.error("结束时间超出场馆运营时间范围!");
                      formRef?.current?.setFieldsValue({
                        startTime: null,
                        endTime: null,
                      });
                    }
                  }}
                  fieldProps={{
                    format: "HH:mm",
                    minuteStep: 15,
                    disabledHours: disabledHours,
                    disabledMinutes: disabledMinutes,
                    getPopupContainer: (triggerNode) =>
                      triggerNode.parentElement,
                  }}
                />
                <ProFormText name="endTime" label=" " readonly />
              </ProForm.Group>
              <ProFormRate
                name="courseDifficulty"
                label="课程难度"
                rules={[{ required: true }]}
                fieldProps={{
                  allowHalf: false,
                }}
              />
              <ProFormColorPicker
                label="排课颜色"
                name="colour"
                fieldProps={{ showText: true, disabledAlpha: true }}
                rules={[{ required: true }]}
                onChange={(e) => {
                  formRef?.current?.setFieldsValue({
                    colour: e.toHexString(),
                  });
                }}
              />
            </>
          )}
        </ProForm>
      </Spin>
    </Drawer>
  );
};
export default AddWork;
